import type { NextFunction, Response, Request } from "express";
import fs from "fs-extra"
import AppError from "../class/AppError.js";
import { getPathFromRoot } from "../util/index.js"

export interface Options {
  matchArr: string[],
  index: string
}

// 传入允许的数组,返回对应 html
export const history = (option: Options) => {
  return (req: Request, res: Response, next: NextFunction) => {

    if (option.matchArr.includes(req.url)) {
      fs.readFile(getPathFromRoot(option.index), 'utf-8', (err, content) => {
        if (err) {
          return next(new AppError(500, "Server handler error, please try again."));
        } else {
          res.set('Content-Type', 'text/html; charset=utf-8')
          res.send(content)
        }
      })
      console.log(req.url);
    } else {
      next()
    }
  }
}
